package com.ruoyi.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JwtUtils {
    private static final String secret = "hand2020";
    private static final Long expiration = 1209600L;

    /**
     * 生成用户token,设置token超时时间
     *这里创建token需要什么数据就可以转什么数据
     */
    public static String createToken(String name,Long userId) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + expiration * 10000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                // 添加头部
                .withHeader(map)
                //可以将基本信息放到claims中
                //userName
                .withClaim("username", name)
                //设置id
                .withClaim("userId", userId)
                //超时设置,设置过期的日期
                .withExpiresAt(expireDate)
                //签发时间
                .withIssuedAt(new Date())
                //SECRET加密
                .sign(Algorithm.HMAC256(secret));
        System.out.println(token);
        return token;
    }

    /**
     * 校验token并解析token
     */
    public static boolean verifyToken(String token) {
        DecodedJWT jwt;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwt = verifier.verify(token);
            System.out.println(
                    "token有效，userName:" + jwt.getClaim("username").asString()
                            + ",签发时间:" + jwt.getIssuedAt()
                            + ",超时时间:" + jwt.getExpiresAt()
            );
            if (jwt.getExpiresAt().before(new Date())) {
                System.out.println("token过期");
                return false;
            }
        } catch (Exception e) {
            //解码异常则抛出异常
            System.out.println("token解析异常:" + e.getMessage());
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        JwtUtils.createToken("赵新雨",5l);
        TokenUser user= JwtUtils.getTokenUser("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzU2MzQ4MjAsInVzZXJJZCI6MjEsImlhdCI6MTczNDQyNTIyMCwidXNlcm5hbWUiOiJhZG1pbiJ9.3aAusElXnlOrwEqgCQgqtCa_Iuvga_SlR8jJ2q5lT9w");
        System.out.println(user);

    }
    public static TokenUser getTokenUser(String token) {
        DecodedJWT jwt;
        TokenUser tokenUser = new TokenUser();
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwt = verifier.verify(token);
            System.out.println(
                    "token有效，userName:" + jwt.getClaim("username").asString()
                            +"`userId:" + jwt.getClaim("userId").asLong()
                            + ",签发时间:" + jwt.getIssuedAt()
                            + ",超时时间:" + jwt.getExpiresAt()
            );
            tokenUser.setUsername(jwt.getClaim("username").asString());
            tokenUser.setId(Math.toIntExact(jwt.getClaim("userId").asLong()));

            if (jwt.getExpiresAt().before(new Date())) {
                if (jwt.getExpiresAt().before(new Date())) {
                    System.out.println("token过期");
                    return null;
                }
            }
        } catch (Exception e) {
            //解码异常则抛出异常
            System.out.println("token解析异常:" + e.getMessage());
            return null;
        }
        return tokenUser;
    }

}
